import { _decorator, Component, dragonBones } from 'cc';
import { app } from 'db://app-game/core/app';
import { Role } from '../Role';
import { RoleDragonBonesList } from '../Role.type';
const { ccclass, property } = _decorator;

/** 角色资源加载 */
@ccclass('RoleViewLoader')
export class RoleViewLoader extends Component {
  role: Role = null!;
  /* 角色上半身龙骨 */
  upperBodyDragonBones: dragonBones.ArmatureDisplay = null!;
  /** 角色下半身龙骨 */
  lowerBodyDragonBones: dragonBones.ArmatureDisplay = null!;

  protected onLoad(): void {
    this.node.on('load', this.onEmitLoad, this);
  }

  private async onEmitLoad(role: Role) {
    this.role = role;
    this.upperBodyDragonBones = role.RoleView!.upperBody.getComponent(dragonBones.ArmatureDisplay);
    this.lowerBodyDragonBones = role.RoleView!.lowerBody.getComponent(dragonBones.ArmatureDisplay);
    let roleDragonBones = role.RoleModelJob.roleDragonBones;
    await this.load(roleDragonBones);
  }

  private async load(roleDragonBones: RoleDragonBonesList) {
    this.node.active = false;
    await this.loadDragonDones(roleDragonBones);
  }

  /** 加载龙骨 */
  private async loadDragonDones(roleDragonBones: RoleDragonBonesList) {
    try {
      const dragonData = await Promise.all([
        app.res.loadAsync(roleDragonBones.upperBody.asset, dragonBones.DragonBonesAsset),
        app.res.loadAsync(roleDragonBones.upperBody.atlasAsset, dragonBones.DragonBonesAtlasAsset),
        app.res.loadAsync(roleDragonBones.lowerBody.asset, dragonBones.DragonBonesAsset),
        app.res.loadAsync(roleDragonBones.lowerBody.atlasAsset, dragonBones.DragonBonesAtlasAsset),
      ]);
      // 1.上半身龙骨赋值
      this.upperBodyDragonBones.dragonAsset = dragonData[0];
      this.upperBodyDragonBones.dragonAtlasAsset = dragonData[1];
      this.upperBodyDragonBones.armatureName = roleDragonBones.upperBody.armatureName;
      this.upperBodyDragonBones.enabled = true;
      this.node.active = true;

      // 2.下半身龙骨赋值
      this.lowerBodyDragonBones.dragonAsset = dragonData[2];
      this.lowerBodyDragonBones.dragonAtlasAsset = dragonData[3];
      this.lowerBodyDragonBones.armatureName = roleDragonBones.lowerBody.armatureName;
      this.lowerBodyDragonBones.enabled = true;
      this.node.active = true;
    } catch (error) {
      console.log(error, '加载骨骼失败', roleDragonBones);
    }
  }
}
